<script lang="ts" setup>
  import { Message, RequestOption, FileItem } from '@arco-design/web-vue';
  import { uploadImage } from '@/api/common';

  const props = defineProps<{
    modelValue?: FileItem[];
    maxSize: number;
    limit: number;
    shouldSquare?: boolean;
  }>();

  const emit = defineEmits(['update:modelValue']);

  const customUploadImage = (options: RequestOption) => {
    const { fileItem, onError, onSuccess } = options;

    const continueUpload = async () => {
      const fd = new FormData();
      fd.append('upload', fileItem.file as File);
      try {
        const res = await uploadImage(fd, new AbortController());
        onSuccess(res.data.data);
      } catch (err) {
        onError('上传失败');
      }
    };

    if (fileItem.file) {
      if (fileItem.file.size > props.maxSize) {
        onError('图片尺寸过大');
        Message.error('图片尺寸过大');
      } else {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(fileItem.file);
        fileReader.onload = () => {
          const img = new Image();
          img.src = fileReader.result as string;
          img.onload = () => {
            if (props.shouldSquare) {
              if (img.width !== img.height) {
                onError('图片比例不正确');
                Message.error('图片比例不正确');
              } else {
                continueUpload();
              }
            } else {
              continueUpload();
            }
          };
        };
      }
    }

    return {};
  };
</script>

<template>
  <a-upload
    :file-list="modelValue"
    list-type="picture-card"
    image-preview
    :custom-request="customUploadImage"
    :limit="limit"
    @change="emit('update:modelValue', $event)"
  />
</template>
